<?php
namespace AuctionCore\Dispute;

class PurchaseOrder
{

    /**
     * 采购单Model
     *
     * @var Model|\Think\Model
     */
    private $purchaseOrderModel;

    /**
     * 采购单号
     *
     * @var string
     */
    private $id;

    /**
     * 构造函数
     *
     * PurchaseOrder constructor.
     * @param string $id 采购单号
     */
    function __construct($id = '')
    {
        $this->purchaseOrderModel = M('purchase_order');
        $this->id = $id;
    }
    /**
     * 根据采购单Id，锁定采购单
     *
     * @param $id 采购单Id
     * @return bool
     */
    public function lockById(){
        $arr = $this->viewById($this->id);

        if($arr['status'] != '1'){
            return false;
        }

        $map =[
            'id' => $this->id,
        ];

        $data = [
            'status' => '2',
            'modify_time' => date('Y-m-d H:i:s', time()),
        ];
        return $this->purchaseOrderModel->where($map)->save($data);
    }
    /**
     * 根据采购单Id，获取采购单详情
     *
     * @return mixed
     */
    public function viewById(){
        $map = [
            'id' => $this->id,
        ];
        $arr = $this->purchaseOrderModel->where($map)->select();
        return $this->sortingData($arr)[0];
    }
    /**
     * 处理数组
     *
     * @param $arr 需要处理的数组
     * @return mixed
     */
    public function sortingData($arr){
        foreach ($arr as $key => $value){
            $status = $value['status']; //采购单状态
            $type = $value['type']; //采购单类型
            $arr[$key]['type_name'] = C('PURCHASE_ORDER_TYPE.'.$type); //类型名称
            $arr[$key]['status_name'] = C('PURCHASE_ORDER_STATUS.'.$status); //状态名称
            $createBy = $value['emp_id'];//创建人
            $arr[$key]['create_by'] = $this->getUserById($createBy)['real_name'];
        }
        return $arr;
    }
    /**
     *  根据员工Id，获取员工信息
     *
     * @param $userId
     * @return mixed
     */
    public function getUserById($userId){
        $m = M("employee");
        $info = $m->find($userId);
        return $info;
    }
    /**
     * 根据采购ID找对应状态付款信息
     * @param   $data
     * @return   payment_id
     */
    public function getPaymentIdByPoid(){
        $data=[];
        $data['pay_type'] = array('in',array(1,2));
        $data['po_id'] = $this->id;
        $purchase_payment = M('purchase_payments')->where($data)->find();
        return $purchase_payment['payment_id'];
    }

}